import { Component } from 'react';

import { ActionSheet, Toast, Boxs, Tab, SearchBar, ScrollList, Avatar, Dialog, Button } from 'saltui';
const { HBox, Box } = Boxs;
const { ButtonGroup } = Button;
import './PageHome.less';

import SelectMember from '../../../../components/selectMember';

import { URLS, nodataIcon } from '../../../../app/variables';

import DB from '../../../../app/db';


let ActionSheetButton;
let indexTab = '0';
const Item = React.createClass({
  action: function () {
    let t = this;
    if (t.props.quesType == 'questionnaireExam') {
      location.hash = 'questionnaire/exam_view/' + t.props.quesId + '/false/' + t.props.createdBy;
    } else {
      let options = [];
      options = ['查看'];
      if (this.props.publish == 1 && this.props.status == 1 && (this.props.isadmin == 1 || this.props.queCreatBy == this.props.user_id)) {
        options.push('回退');
      }
      ActionSheetButton = ActionSheet.show({
        options: options,
        destructiveButtonIndex: indexTab == '0' ? 1 : 0,
        maskClosable: true,
      }, (index) => {
        DB.QuesModuleAPI.entityIsExist({ id: t.props.quesId }).then((content) => {
          if (content == 'exist') {
            if (index == 0) {
              location.hash = 'questionnaire/ques_info/' + t.props.quesId + "/1/false/1/" + t.props.createdBy;
            }
            if (index == 1) {//回退
              location.hash = 'questionnaire/back_reason/' + t.props.quesId + "/" + t.props.id + "/edit";
            }
          } else {
            Toast.show({
              type: 'error',
              content: '当前数据已删除',
            });
            history.back();
          }
        }).catch((error) => {
        });
      })
    }
  },

  render: function () {
    //type处理
    function formatType(type) {
      switch (type) {
        case '1': return '已提交';
        case '2': return '草稿';
        case '3': return '已回退';
        case '4': return '已提交';
        case 1: return '已提交';
        case 2: return '草稿';
        case 3: return '已回退';
        case 4: return '已提交';
      }
    }
    let token = getLoginUserInfo().token;
    var context = document.getElementById("officeContext").value;
    let url = context + '/dingisv/api/common/viewImage?fid=';
    let orgName = this.props.orgunitname;
    if(!!orgName && orgName.length > 6){
      orgName = orgName.substring(0, 6) + "...";
    }
    return <div onClick={this.action}>
      <HBox vAlign="center" className="dd-bottom-border t-PT20 t-PB20 t-BCf t-PL16 t-PR16">
        <HBox flex={1} vAlign="center">
          <Box className="t-MR10 t-R50 t-OFH">
            {this.props.image == '' ?
              <Avatar name={!this.props.userName?'':this.props.userName} size={50} />
              :
              <Avatar src={url + this.props.image + '&token=' + token} size={50} />
            }
          </Box>
          <Box flex={1}>
            <HBox className="t-FS16 t-MB6">
              <Box>
                <span>{!this.props.userName?'':this.props.userName}</span>
                <span className="t-FS14 t-ML10 t-MR10 t-FCddfontblue-30">|</span>
                <span>{!orgName?'':orgName}</span>
              </Box>
            </HBox>
            <Box className="t-FS14 t-FCddfontblue-40">{this.props.createdDate.substring(0, 10)}</Box>
          </Box>

        </HBox>
      </HBox>
      {/* <Box className="t-BCf t-ML16 t-MR16 t-MT10 t-P12 t-PR0 t-R4">
        <HBox vAlign="center">
          <HBox flex={1} vAlign="center" className="t-LH1_4 t-PR10 t-FS16">
            <Box className="t-MAXW-78 t-omit">{this.props.userName}</Box>
            <Box className="t-FCddfontblue-10 t-ML4 t-MR4 t-FS12">|</Box>
            <Box className="t-FCddfontblue-40 t-FS14 t-omit" flex={1}>{this.props.orgunitname}</Box>
          </HBox>
          <Box className={this.props.status==1||this.props.status==4?"t-FAC t-RL12 t-BCgreyblue-20 t-FCf t-H22 t-LH22 t-FS12 t-W56":"t-FAC t-RL12  t-BCcyan t-FCf t-H22 t-LH22 t-FS12 t-W56"}>{formatType(this.props.status)}</Box>
        </HBox>
        <HBox vAlign="center" className="t-MT8 t-FCddfontblue-40">
          <Box flex={1}>{this.props.createdDate.substring(0,10)}</Box>
          <Box><b className="iconfont icon-more t-FS18 t-PR16"></b></Box>
        </HBox>
      </Box> */}
    </div>;
  }
});

const Item2 = React.createClass({
  setCheckBoxStatus : function (event) {
    let count = 0;
    if (this.props.isBatch) {//批量状态
      if(!this.props.isBatchSelect){
        //let checkDiv = $(event.currentTarget).find(".t-checkbox-field-icon-list");
        let checkDiv = $(event.currentTarget);
        if(checkDiv.hasClass("un-checked")){//判断是否未选中
          checkDiv.removeClass("un-checked");
          checkDiv.addClass("checked");
          count += 1;
        }else{
          checkDiv.removeClass("checked");
          checkDiv.addClass("un-checked");
          count = count - 1;
        }
        this.props.selectPersonClick(count);
       }
    }
  },

  action: function () {
    let t = this;
    let id = t.props.id;
    let qId = t.props.qId;
    // let options = ['提醒'];
    // ActionSheetButton = ActionSheet.show({
    //     options: options,
    //     destructiveButtonIndex:indexTab=='0'?1:0,
    //     maskClosable: true,
    //   }, (index) => {
    DB.QuesModuleAPI.entityIsExist({ id: qId }).then((content) => {
      if (content == 'exist') {
        // if(index == 0){
        Dialog.confirm({
          title: '提示',
          locale: 'zh_CN',
          content: '确定要提醒吗?',
          onConfirm() {
            DB.QuesModuleAPI.telSendMessage({
              userId: id,
              quesId: qId
            }).then((content) => {
              Toast.show({
                type: 'success',
                content: '提醒发送成功',
                onHide: function () { }
              });
            }).catch();
          },
          onCancel() { },
        });
        // }
      } else {
        Toast.show({
          type: 'error',
          content: '当前数据已删除',
        });
        history.back();
      }
    }).catch((error) => {
    });
    // })
  },

  render: function () {
    let token = getLoginUserInfo().token;
    var context = document.getElementById("officeContext").value;
    let url = context + '/dingisv/api/common/viewImage?fid=';
    let orgName = this.props.orgName;
    if(!!orgName && orgName.length > 6){
      orgName = orgName.substring(0, 6) + "...";
    }
    return <div >
      <HBox vAlign="center" className="dd-bottom-border t-PT20 t-PB20 t-BCf t-PL16 t-PR16">
        <HBox flex={1} vAlign="center">
          <Box className={this.props.isBatch?(this.props.isBatchSelect?'t-checkbox-field-icon-list checked t-MR10':'t-checkbox-field-icon-list un-checked t-MR10'):'t-DN'} onClick={this.setCheckBoxStatus.bind(this)} data-id={this.props.id}>
              <i className="iconfont icon-checked t-FCf t-FS14"></i>
          </Box>
          <Box className="t-MR10 t-R50 t-OFH">
            {this.props.image == '' ?
              <Avatar name={!this.props.userName?'':this.props.userName} size={50} />
              :
              <Avatar src={url + this.props.image + '&token=' + token} size={50} />
            }
          </Box>
          <Box flex={1}>
            <HBox vAlign="center" className="t-FS16 t-MB6">
              <Box>
                <span>{!this.props.userName?'':this.props.userName}</span>
                <span className="t-FS12 t-ML10 t-MR10 t-FCddfontblue-40">|</span>
                <span>{!orgName?'':orgName}</span>
              </Box>
            </HBox>
            <Box className="t-FS14 t-FCddfontblue-40">{this.props.closeDate.substring(0, 10)}</Box>
          </Box>
        </HBox>
        <Box className="dd-icon-notice" onClick={this.action}>
          <span className="iconfont icon-bell"></span>
        </Box>
      </HBox>

      {/* <Box className="t-BCf t-ML16 t-MR16 t-MT10 t-P12 t-PR0 t-R4">
        <HBox vAlign="center">
          <HBox flex={1} vAlign="center" className="t-LH1_4 t-PR10 t-FS16">
            <Box className="t-MAXW-78 t-omit">{this.props.userName}</Box>
            <Box className="t-FCddfontblue-10 t-ML4 t-MR4 t-FS12">|</Box>
            <Box className="t-FCddfontblue-40 t-FS14 t-omit" flex={1}>{this.props.orgName}</Box>
          </HBox>
          <Box onClick={this.action}><b className="iconfont icon-bell t-FS18 t-PR16"></b></Box>
        </HBox>
        <HBox vAlign="center" className="t-MT8 t-FCddfontblue-40">
          <Box flex={1}>{this.props.closeDate.substring(0,10)}</Box>
        </HBox>
      </Box> */}
    </div>;
  }
});

export default class PageHome extends Component {

  constructor(props) {
    super(props);
    let t = this;
    let userId = document.getElementById("userHiddenId").value;
    let winHeight;
    winHeight = getScrollHigh(1, 1, 0);
    let quesType = this.props.params.type;
    indexTab = '0';
    this.state = {
      id: this.props.params.id,

      userId: userId,
      ableClick: true,
      activeIndex: 0,
      activeTabIndex: '0',
      winHeight: winHeight,
      search1: '',
      search2: '',
      orgId1: [],
      orgId2: [],
      quesType: quesType,
      //搜索
      visible1: false,

      //答卷状态   只展示两种
      anStatusArr: [{ 'value': '1', 'text': '已提交' }, { 'value': '3', 'text': '已退回' }],

      // //问卷类型
      // typeArr:[{'value':'questionnaireVote','text':'投票'},{'value':'questionnaireSurvey','text':'调查'},{'value':'questionnaireExam','text':'考试'}],
      // //问卷状态
      // publishArr:[{'value':'1','text':'已发布'},{'value':'0','text':'未发布'}],


      status: "",
      //选择的问卷类型
      // type:"",
      //选择的问卷状态
      // publish:"",

      //筛选条件展示位
      anStatusArrow: false,
      //筛选条件展示位
      // quesTypeArrow : false,
      // quesPublishArrow : false,

      //筛选  问卷时间
      // time:null,
      // startDate:null,
      // endDate:null,
      noDataTip1: '暂无数据',
      noDataTip2: '暂无数据',
      isBatch:false, // 批量操作标记
      isBatchSelect:false, // 批量选择标记
      selectPersonCount:'0',//已选用户数量
      personTotal:0 //列表总数
    };
    
    if(quesType == "questionnaireExam"){
      setTitle('答卷列表');    
    }else
      setTitle('详细数据');    
  }

  //时间格式化   YYYY-MM-DD
  // formatterDate(time){
  //   var date = new Date(time);
  //   var Y = date.getFullYear() + '-';
  //   var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  //   var D = date.getDate() < 10 ? "0" + (date.getDate()) : date.getDate();
  //   return Y+M+D;
  // }

  componentDidMount() {
    searchBarLimit(20);
  }

  //组件销毁执行
  componentWillUnmount() {
    if (ActionSheetButton) {
      ActionSheetButton.close();
    }
  }

  //分页列表请求前
  beforeFetch1(data, form) {
    let search = form.value;
    if (search == undefined) {
      data.search = this.state.search1;
    } else {
      data.search = form.value;
    }
    // let rows = data.pageSize;
    // data.rows = rows;

    // if(this.state.startDate != null && this.state.startDate != ''){
    //   data.startDate = this.formatterDate(this.state.startDate);
    // }
    // if(this.state.endDate != null && this.state.endDate != ''){
    //   data.endDate = this.formatterDate(this.state.endDate);

    // }
    // if(this.state.type != ''){
    //   data.quesType = this.state.type;
    // }
    if (this.state.orgId1 != '' && this.state.orgId1 != []) {
      let orgs = this.state.orgId1;
      let orgIds = '';
      for (let i = 0; i < orgs.length; i++) {
        orgIds += orgs[i].scopeValue + ',';
      }
      data.orgId = orgIds.substring(0, orgIds.length - 1);
    }
    data.quesId = this.state.id;
    return data;
  }

  //分页列表请求前
  beforeFetch2(data, form) {
    let search = form.value;
    if (search == undefined) {
      data.search = this.state.search2;
    } else {
      data.search = form.value;
    }
    if (this.state.orgId2 != '' && this.state.orgId2 != []) {
      let orgs = this.state.orgId2;
      let orgIds = '';
      for (let i = 0; i < orgs.length; i++) {
        orgIds += orgs[i].scopeValue + ',';
      }
      data.orgId = orgIds.substring(0, orgIds.length - 1);
    }
    data.quesId = this.state.id;
    return data;
  }


  //初始化按钮
  initButton() {
    //设置帮助
    //  dd.biz.navigation.setIcon({
    //     showIcon : true,//是否显示icon
    //     iconIndex : 2,//显示的iconIndex,如上图
    //     onSuccess : function(result) {
    //         /*结构
    //         {
    //         }*/
    //         //点击icon之后将会回调这个函数
    //         location.hash='document/help_index';
    //     },
    //     onFail : function(err) {
    //     //jsapi调用失败将会回调此函数
    //     }
    // });

  }

  /*跳到帮助*/
  skipHelp(path) {
    let t = this;
    var userId = this.state.userId;
    dd.util.domainStorage.setItem({
      name: 'document_' + userId, // 存储信息的key值
      value: 'isLogin', // 存储信息的Value值
      onSuccess: function (info) {
        t.setState({
          isMask: false
        });
        location.hash = path;
      },
      onFail: function (err) {
      }
    });

  }
  //刷新列表
  refresh() {
    let t = this;
    let value1 = t.state.search1;
    let value2 = t.state.search2;
    if (indexTab == "0") {
      t.fetchData({ value: value1, orgId: this.state.orgId1 });
    } else {
      t.fetchData({ value: value2, orgId: this.state.orgId2 });
    }
  }
  //改变筛选展示状态
  changeArrow(field) {
    let t = this;
    let status = t.state[field];
    t.setState({
      [field]: !status
    })
  }


  //修改标题
  changeTitle(title) {
    dd.biz.navigation.setTitle({
      title: title,//控制标题文本，空字符串表示显示默认文本
      onSuccess: function (result) { },
      onFail: function (err) { }
    });
  }

  //日期选择确认
  // onOk(value,key){
  //   let t = this;
  //   if(key == "startDate" && t.state.endDate != null && t.state.endDate != ''){
  //     if(t.formatterDate(t.state.endDate) < t.formatterDate(value.value)){
  //       Toast.show({
  //         type: 'error',
  //         content: '开始日期不能大于结束日期'
  //       });
  //       return;
  //     }
  //   }
  //   if(key == "endDate" && t.state.startDate != null && t.state.startDate != ''){
  //     if(t.formatterDate(t.state.startDate) > t.formatterDate(value.value)){
  //       Toast.show({
  //         type: 'error',
  //         content: '结束日期不能小于开始日期'
  //       });
  //       return;
  //     }
  //   }
  //   t.setState({
  //     [key]:t.formatterDate(value.value)
  //   });
  // }

  showSlot(id) {
    this[id].show();
  }

  changeTab(data) {
    let index = parseInt(data.activeKey);
    indexTab = index + "";
    this.setState({
      orgId1: [],
      orgId2: []
    }, () => {
      this.refs.org_ref1.dialogClearItem(false);
      this.refs.org_ref2.dialogClearItem(false);
    });
    searchBarLimit(20);
  }

  handleTabClick(data) {
    let index = parseInt(data.activeKey);
    indexTab = index + "";
  }

  fetchData(param) {
    if (indexTab == "0") {
      this.refs.reportComment_ref1.fetchData(param);
    } else if (indexTab == "1") {
      this.refs.reportComment_ref2.fetchData(param);
    }
  }

  getPerson1(value, type) {
    if (value != "" && value != null) {
      this.setState({
        orgId1: value,
        noDataTip1: '无搜索结果'
      }, () => {
        this.refresh();
      });
    } else {
      this.refresh();
    }
  }

  getPerson2(value, type) {
    if (value != "" && value != null) {
      this.setState({
        orgId2: value,
        noDataTip2: '无搜索结果'
      }, () => {
        this.refresh();
      });
    } else {
      this.refresh();
    }
  }

  //点击批量
  clickBatch(boolean){
    this.setState({
      isBatch: !boolean,
      selectPersonCount:'0',
      isBatchSelect:false
    });
  }

  //批量状态下，获取选中的人员数量
  selectPersonClick(count){
    let selectPersonCount = parseInt(this.state.selectPersonCount==''?'0':this.state.selectPersonCount);
    selectPersonCount += count;
    this.setState({
      selectPersonCount:selectPersonCount
    });
  }

  //点击全选
  batchClick(boolean) {  
    let personTotal = '';//this.state.personTotal; 
    if(boolean){
      personTotal = '0';
    }else{
      personTotal = this.state.personTotal;
    }
    this.setState({
      isBatchSelect: !boolean,
      selectPersonCount:personTotal
    });
  }

  returnData(data){ 
    this.setState({
      personTotal:data.personTotal
    });
    return data;
  }

  // 批量提醒
  batchRemindClick(){
    let t = this;
    //遍历循环选中  
    var ids = "";  
    $(".checked").map(function(index,item){
      ids += $(item).attr("data-id")+","; 
    });
    if(ids){
      ids = ids.substring(0,ids.length-1); 
    }else{ 
      return;
    }
    let qId = this.state.id;
    let isBatchSelect = this.state.isBatchSelect;
    DB.QuesModuleAPI.entityIsExist({ id: qId }).then((content) => {
      if (content == 'exist') {
        Dialog.confirm({
          title: '提示',
          locale: 'zh_CN',
          content: '确定要提醒吗?',
          onConfirm() {
            DB.QuesModuleAPI.telSendMessage({
              userId: ids,
              quesId: qId,
              isBatchSelect : isBatchSelect
            }).then((content) => {
              Toast.show({
                type: 'success',
                content: '提醒发送成功',
                onHide: function () { }
              });
              t.setState({isBatch:false,isBatchSelect:false});
            }).catch();
          },
          onCancel() { },
        });
      } else {
        Toast.show({
          type: 'error',
          content: '当前数据已删除',
        });
        history.back();
      }
    }).catch((error) => {
    });
  }

  render() {
    const t = this;
    let popHei = window.screen.height - 60;
    const props1 = {
      locale: 'zh_CN',
      instantSearch: false,
      placeholder: '请输入答卷人员名称',
      hasHistory: true,
      searchDelay: 450,
      onEnter: (value) => { console.log(value); },
      onExit: () => {
        t.setState({
          search1: '',
          noDataTip1: '暂无数据'
        }, () => {
          t.refs.reportComment_ref1.fetchData("top");
        });

      },
      onChange: (value) => {
        console.log('onChange');
      },
      onSearch: (value) => {
        t.setState({
          search1: value,
          noDataTip1: '无搜索结果'
        }, () => {
          if (value != "") t.refs.reportComment_ref1.fetchData({ value: value });
        });
      }
    };
    const props2 = {
      locale: 'zh_CN',
      instantSearch: false,
      placeholder: '请输入答卷人员名称',
      hasHistory: true,
      searchDelay: 450,
      onEnter: (value) => { console.log(value); },
      onExit: () => {
        t.setState({
          search2: '',
          noDataTip2: '暂无数据'
        }, () => {
          t.refs.reportComment_ref2.fetchData("top");
        });

      },
      onChange: (value) => {
        console.log('onChange');
      },
      onSearch: (value) => {
        $(".checked").map(function(index,item){
          $(item).attr("class","t-checkbox-field-icon-list un-checked t-MR10"); 
        });
        t.setState({
          search2: value,
          noDataTip2: '无搜索结果'
        }, () => {
          if (value != "") t.refs.reportComment_ref2.fetchData({ value: value });
        });
      }
    };
    let winHeightStyle = { height: this.state.winHeight };
    let winHeights = getScrollHigh(1, 0, 0);
    let s = { height: winHeights };
    const datetimeProps = {
      locale: 'zh-cn',
    };
    return (
      <div>
        <Tab destroyInactiveTabPane={false} activeKey={indexTab} onTabClick={this.handleTabClick.bind(this)} onChange={t.changeTab.bind(t)}>
          {/*<Tab.Item title={"统计结果"} >
              <div style={s}>
                <Results quesId={t.state.id}/>
              </div>
          </Tab.Item>*/}
          <Tab.Item title={"已答"}>
            <div>
              <HBox className="t-BCf" vAlign="center">
                <Box flex={1}><SearchBar {...props1} /></Box>
                <Box className="t-FCddblue" onClick={() => { t.refs.org_ref1.initSelectData(); t.refs.org_ref1.clickAdd(); }}><i className="iconfont icon-filter t-FS18 t-FCblue t-LH44 t-PR10" /></Box>
              </HBox>
              <div style={winHeightStyle}>
                <ScrollList
                  url={URLS.getStatisticsPersonList}
                  dataType="json"
                  pageSize={10}
                  beforeFetch={this.beforeFetch1.bind(this)}
                  noDataTip={this.state.noDataTip1}
                  processData={(data) => data}
                  ref='reportComment_ref1'
                  noDataImage={nodataIcon}
                  currentPageKey="page"
                >
                  <Item quesType={t.state.quesType} refresh={t.refresh.bind(t)} />
                </ScrollList>
              </div>
            </div>
          </Tab.Item>
          <Tab.Item title={"未答"}>
            <div>
              <HBox className="t-BCf" vAlign="center">
                <Box flex={1}><SearchBar {...props2} /></Box>
                {/* <Box className="t-FCddblue" onClick={() => { t.refs.org_ref2.initSelectData(); t.refs.org_ref2.clickAdd(); }}><i className="iconfont icon-filter t-FS18 t-FCblue t-LH44 t-PR10" /></Box> */}
                <Box className="t-FS14 t-FCddblue t-PR16" onClick={this.clickBatch.bind(this,this.state.isBatch)}>{this.state.isBatch ? '关闭' : '批量'}</Box>
              </HBox>
              <div style={winHeightStyle}>
                <ScrollList
                  url={URLS.getNoAnwserPersonList}
                  dataType="json"
                  pageSize={10}
                  beforeFetch={this.beforeFetch2.bind(this)}
                  noDataTip={this.state.noDataTip2}
                  processData={this.returnData.bind(this)}
                  ref='reportComment_ref2'
                  noDataImage={nodataIcon}
                  currentPageKey="page"
                >
                  <Item2 qId={this.state.id} refresh={t.refresh.bind(t)} isBatch={this.state.isBatch} isBatchSelect={this.state.isBatchSelect} selectPersonClick={this.selectPersonClick.bind(this)} />
                </ScrollList>
              </div>
            </div>
          </Tab.Item>
        </Tab>
        <div className="t-DN">
          <SelectMember label="所属组织" checkType="checkbox" code="org" chooseType="userAndOrg" showType="list" defaultValue={this.state.orgId1} required={false} ref="org_ref1"
            isDelete={true} onChange={(value) => { this.getPerson1(value, 'ques'); }} />
        </div>
        <div className="t-DN">
          <SelectMember label="所属组织" checkType="checkbox" code="org" showType="list" defaultValue={this.state.orgId2} required={false} ref="org_ref2"
            isDelete={true} onChange={(value) => { this.getPerson2(value, 'ques'); }} />
        </div>
        <div className={this.state.isBatch ? 't-P0 t-bottom-fixed no-top-border dd-batch-checkbox' : 't-DN'}>
          <ButtonGroup>
            <Button type="secondary" display="banner"  className="dd-checkbox-icon t-FC3"  onClick={this.batchClick.bind(this,this.state.isBatchSelect)} >
              <span className={this.state.isBatchSelect ? 'dd-checked-button-icon dd-batch-button-icon' : 'dd-batch-button-icon'}>
                <i className={this.state.isBatchSelect ? 'iconfont icon-checked' : 't-DN'}></i>
              </span>
              全选
            </Button>
            {this.state.selectPersonCount == "0" ? 
             <Button disabled type="primary" display="banner" onClick={this.batchRemindClick.bind(this)}>提醒</Button> 
             : 
             <Button type="primary" display="banner" onClick={this.batchRemindClick.bind(this)}>提醒</Button>}
          </ButtonGroup>
        </div>
      </div>
    );
  }
}


